using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using UnityEngine.Networking;

public class DialogueManager : singleTon<DialogueManager>
{
    [Header("Basic Element")] 
    public Image Icon;

    public Text text;

    public Button nextBtn;
    public GameObject dialoguePanel;

    public RectTransform optionPanel;
    public OptionUI optionPrefab;

    [Header("Data")] 
    public DialogueData_SO currentData;

    private int currentIndex = 0;

    protected override void Awake()
    {
        base.Awake();
        nextBtn.onClick.AddListener(ContinueDialogue);
    }

    private void ContinueDialogue()
    {
        if(currentIndex<currentData.DialogPieces.Count)
        {
            updateDialougueUI(currentData.DialogPieces[currentIndex]);
        }
        else
        {
            dialoguePanel.SetActive(false);
        }
    }

    public void updateDialogueData(DialogueData_SO data)
    {
        currentData = data;
        currentIndex = 0;
    }

    public void updateDialougueUI(DialoguePiece piece)
    {
        dialoguePanel.SetActive(true);
        currentIndex++;

        if (piece.headslot != null)
        {
            Icon.enabled = true;
            Icon.sprite = piece.headslot;
        }
        else
        {
            Icon.enabled = false;
        }

        text.text = "";
        text.DOText(piece.text, 1f);

        if (piece.DialogOptions.Count == 0 && currentData.DialogPieces.Count > 0)
        {
            nextBtn.interactable = true;
            nextBtn.gameObject.SetActive(true);
            nextBtn.transform.GetChild(0).gameObject.SetActive(true);
        }
        else
        {
            nextBtn.interactable = false;
            nextBtn.transform.GetChild(0).gameObject.SetActive(false);
        }
        
        //创建options
        CreateOptions(piece);
    }

    private void CreateOptions(DialoguePiece piece)
    {
        if (optionPanel.childCount > 0)
        {
            for (int i = 0; i < optionPanel.childCount; i++)
            {
                Destroy(optionPanel.GetChild(i).gameObject);
            }
        }

        for (int i = 0; i < piece.DialogOptions.Count; i++)
            {
                var option = Instantiate(optionPrefab, optionPanel);
                option.updateOption(piece,piece.DialogOptions[i]);
            }
        
    }
}
